package com.tanhua.autoconfig.templates;

import com.baidu.aip.face.AipFace;
import com.baidu.aip.util.Base64Util;
import com.tanhua.autoconfig.properties.AipFaceProperties;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Base64Utils;

import javax.annotation.PostConstruct;
import java.util.HashMap;

public class AipFaceTemplate implements InitializingBean {


    private AipFaceProperties properties;

    public AipFaceTemplate(AipFaceProperties properties) {
        this.properties = properties;
    }

    public boolean detect(byte [] body) {

        AipFace client = new AipFace(properties.getAppId(), properties.getApiKey(), properties.getSecretKey());
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("face_field", "age");
        options.put("max_face_num", "2");
        options.put("face_type", "LIVE");
        options.put("liveness_control", "LOW");


        String imageType = "BASE64";

        String image = Base64Util.encode(body);

        // 人脸检测
        JSONObject res = client.detect(image, imageType, options);

        int code = res.getInt("error_code");

        return code == 0;
    }

    /**
     * 人脸比对 霍 2021-7-16
     * @param imageBytes 前端传入的base64编码图片
     * @return 查询到的用户id
     */
    public Long isRegister(byte[] imageBytes) {
        AipFace client = new AipFace(properties.getAppId(), properties.getApiKey(), properties.getSecretKey());
        HashMap<String, String> options = new HashMap<>();
        options.put("quality_control", "LOW");// 图片质量控制
        options.put("liveness_control", "LOW");//活体检测控制
        options.put("max_user_num", "1"); // 查找后返回的用户数量,返回相似度最高的几个用户
        String imageBase64 = Base64Utils.encodeToString(imageBytes);
        JSONObject res = client.search(imageBase64, "BASE64", "tanhua", options);
        System.out.println(res.toString());
        if(res.has("error_code") && res.getInt("error_code")==0) {
            JSONObject result = res.getJSONObject("result");
            JSONArray userList = result.getJSONArray("user_list");
            if(userList.length()>0) {
                JSONObject user = userList.getJSONObject(0);
                double score = user.getDouble("score");
                if (score > 80)
                    return Long.valueOf(user.getString("user_id"));
            }
        }
        return null;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("AipFaceTemplate初始化完成....");
    }
}